package com.zhtx.debt.customer.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhtx.debt.customer.entity.*;
import com.zhtx.debt.customer.repository.*;
import com.zhtx.debt.customer.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description: 个债客户历史数据抽取到企债
 * @author: liujin
 * @create: 2020-05-07 10:26
 */
@Slf4j
@Service
@Transactional
public class CustomerService {

    @Resource
    private ZsCustomerCopy1Repository zsCustomerCopy1Repository;

    @Resource
    private ZsCustomerRepository zsCustomerRepository;

    @Resource
    private ZsCustomerReviewCopy1Repository zsCustomerReviewCopy1Repository;

    @Resource
    private ZsCustomerReviewRepository zsCustomerReviewRepository;

    @Resource
    private ZsCustomerVersionCopy1Repository zsCustomerVersionCopy1Repository;

    @Resource
    private ZsCustomerVersionRepository zsCustomerVersionRepository;

    @Resource
    private ZsCustomerAttachRepository zsCustomerAttachRepository;

    @Resource
    private DebtEqbAccountRepository debtEqbAccountRepository;

    @Resource
    private ZsEqbAccountRepository zsEqbAccountRepository;

    @Resource
    private ZsZjEqbAccountRepository zjEqbAccountRepository;

    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1L, 1L);

    @Resource
    private DebtEqbAccountZjRepository debtEqbAccountZjRepository;


    public void convert() {
        log.info("开始导入");

        List<ZsCustomerCopy1> customerCopy1List = zsCustomerCopy1Repository.findAll();
        List<ZsCustomer> customerList = customerCopy2customer(customerCopy1List);

        List<ZsCustomerVersionCopy1> versionCopy1List = zsCustomerVersionCopy1Repository.findAll();
        List<ZsCustomerVersion> versionList = versionCopy2version(versionCopy1List);

        List<ZsCustomerReviewCopy1> reviewCopy1List = zsCustomerReviewCopy1Repository.findAll();
        List<ZsCustomerReview> reviewList = reviewCopy2review(reviewCopy1List);

        List<ZsEqbAccount> zsEqbAccountList = zsEqbAccountRepository.findAll();
        List<DebtEqbAccount> debtEqbAccountList = zsEqbAccount2debtEqb(zsEqbAccountList);

        List<ZsZjEqbAccount> zsZjEqbAccountList = zjEqbAccountRepository.findAll();
        List<DebtEqbAccountZj> debtEqbAccountZjList = zsZjEqbAccoun2debtEqb(zsZjEqbAccountList);


        List<ZsCustomerAttach> attachList = new LinkedList<>();

        replaceId(customerList, versionList, reviewList, attachList, debtEqbAccountList, debtEqbAccountZjList);

        log.info("保存 customerList");
        zsCustomerRepository.saveAll(customerList);

        log.info("保存 versionList");
        zsCustomerVersionRepository.saveAll(versionList);

        log.info("保存 Attach");
        zsCustomerAttachRepository.saveAll(attachList);

        log.info("保存 reviewList");
        zsCustomerReviewRepository.saveAll(reviewList);

        log.info("保存 E ZH签宝信息");
        debtEqbAccountRepository.saveAll(debtEqbAccountList);

        log.info("保存 E ZJ签宝信息");
        debtEqbAccountZjRepository.saveAll(debtEqbAccountZjList);
    }

    private List<DebtEqbAccountZj> zsZjEqbAccoun2debtEqb(List<ZsZjEqbAccount> zsZjEqbAccountList) {
        List<DebtEqbAccountZj> list = new LinkedList<>();
        for (ZsZjEqbAccount zsZjEqbAccount : zsZjEqbAccountList) {
            DebtEqbAccountZj debtEqbAccount = new DebtEqbAccountZj();
            debtEqbAccount.setId(zsZjEqbAccount.getId());
            debtEqbAccount.setCustId(zsZjEqbAccount.getId());
            debtEqbAccount.setCustomerName(zsZjEqbAccount.getEqName());
            debtEqbAccount.setIdNo(zsZjEqbAccount.getEqIdcard());
            debtEqbAccount.setMobile(zsZjEqbAccount.getEqMobile());
            debtEqbAccount.setAuthServiceid(zsZjEqbAccount.getAuthServiceid());
            debtEqbAccount.setEqAccountId(zsZjEqbAccount.getEqAccountid());
            debtEqbAccount.setFaceAccountId(zsZjEqbAccount.getFaceAccountId());
            debtEqbAccount.setEqBase64(zsZjEqbAccount.getEqBase64());
            debtEqbAccount.setRemark(zsZjEqbAccount.getRemark());
            debtEqbAccount.setCreateBy("");
            debtEqbAccount.setCreateDate(zsZjEqbAccount.getCreateDate());
            debtEqbAccount.setCreateName("");
            list.add(debtEqbAccount);
        }
        return list;
    }

    private List<DebtEqbAccount> zsEqbAccount2debtEqb(List<ZsEqbAccount> zsEqbAccountList) {
        List<DebtEqbAccount> list = new LinkedList<>();
        for (ZsEqbAccount zsEqbAccount : zsEqbAccountList) {
            DebtEqbAccount debtEqbAccount = new DebtEqbAccount();
            debtEqbAccount.setId(zsEqbAccount.getId());
            debtEqbAccount.setCustId(zsEqbAccount.getId());
            debtEqbAccount.setCustomerName(zsEqbAccount.getEqName());
            debtEqbAccount.setIdNo(zsEqbAccount.getEqIdcard());
            debtEqbAccount.setMobile(zsEqbAccount.getEqMobile());
            debtEqbAccount.setAuthServiceid(zsEqbAccount.getAuthServiceid());
            debtEqbAccount.setEqAccountId(zsEqbAccount.getEqAccountid());
            debtEqbAccount.setFaceAccountId(zsEqbAccount.getFaceAccountId());
            debtEqbAccount.setEqBase64(zsEqbAccount.getEqBase64());
            debtEqbAccount.setRemark(zsEqbAccount.getRemark());
            debtEqbAccount.setCreateBy("");
            debtEqbAccount.setCreateDate(zsEqbAccount.getCreateDate());
            debtEqbAccount.setCreateName("");
            list.add(debtEqbAccount);
        }
        return list;
    }

    private void replaceId(List<ZsCustomer> customers, List<ZsCustomerVersion> versions, List<ZsCustomerReview> reviews, List<ZsCustomerAttach> attachList, List<DebtEqbAccount> debtEqbAccountList, List<DebtEqbAccountZj> debtEqbAccountZjList) {
        List<ZsCustomer> tempCustomers = new LinkedList<>();
        List<ZsCustomerVersion> tempVersions = new LinkedList<>();
        List<ZsCustomerReview> tempReviews = new LinkedList<>();
        List<DebtEqbAccount> tempDebtEqbs = new LinkedList<>();
        List<DebtEqbAccountZj> tempZjDebtEqbs = new LinkedList<>();

        for (ZsCustomer zsCustomer : customers) {
            String customerId = zsCustomer.getId();
            String newCustomerId = getId();
            String customerVersionId = zsCustomer.getCustomerVersionId();
            zsCustomer.setId(newCustomerId);

            List<ZsCustomerVersion> versionList = versions.stream().filter(v -> v.getCustomerId().equals(customerId)).collect(Collectors.toList());
            for (ZsCustomerVersion version : versionList) {
                String versionId = version.getId();
                String newVersionId = getId();
                version.setCustomerId(newCustomerId);
                version.setId(newVersionId);

                builderFile(version.getFile(), attachList, newVersionId);

                if (Objects.equals(customerVersionId, versionId)) {
                    zsCustomer.setCustomerVersionId(newVersionId);
                    tempCustomers.add(zsCustomer);
                }
                tempVersions.add(version);

                Optional<ZsCustomerReview> reviewOptional = reviews.stream().filter(rev -> rev.getCustomerVersionId().equals(versionId)).findFirst();
                if (reviewOptional.isPresent()) {
                    ZsCustomerReview review = reviewOptional.get();
                    review.setId(getId());
                    review.setCustomerVersionId(newVersionId);
                    review.setDepartName(version.getDepartName());
                    tempReviews.add(review);
                }
            }

            Optional<DebtEqbAccount> debtEqbOptional = debtEqbAccountList.stream().filter(eqb -> Objects.equals(customerId, eqb.getCustId())).findFirst();
            if (debtEqbOptional.isPresent()) {
                DebtEqbAccount debtEqbAccount = debtEqbOptional.get();
                debtEqbAccount.setId(getId());
                debtEqbAccount.setCustId(newCustomerId);
                debtEqbAccount.setCreateDate(debtEqbAccount.getCreateDate() == null ? LocalDateTime.now() : debtEqbAccount.getCreateDate());
                debtEqbAccount.setMobile(debtEqbAccount.getMobile() == null ? "" : debtEqbAccount.getMobile());
                tempDebtEqbs.add(debtEqbAccount);
            }

            Optional<DebtEqbAccountZj> zjEqbAccountOptional = debtEqbAccountZjList.stream().filter(eqb -> Objects.equals(customerId, eqb.getCustId())).findFirst();
            if (zjEqbAccountOptional.isPresent()) {
                DebtEqbAccountZj debtEqbAccountZj = zjEqbAccountOptional.get();
                debtEqbAccountZj.setId(getId());
                debtEqbAccountZj.setCustId(newCustomerId);
                debtEqbAccountZj.setCreateDate(debtEqbAccountZj.getCreateDate() == null ? LocalDateTime.now() : debtEqbAccountZj.getCreateDate());
                debtEqbAccountZj.setMobile(debtEqbAccountZj.getMobile() == null ? "" : debtEqbAccountZj.getMobile());
                tempZjDebtEqbs.add(debtEqbAccountZj);
            }
        }

        customers.clear();
        customers.addAll(tempCustomers);

        versions.clear();
        versions.addAll(tempVersions);

        reviews.clear();
        reviews.addAll(tempReviews);

        debtEqbAccountList.clear();
        debtEqbAccountList.addAll(tempDebtEqbs);

        debtEqbAccountZjList.clear();
        debtEqbAccountZjList.addAll(tempZjDebtEqbs);
    }

    private void builderFile(String file, List<ZsCustomerAttach> attachList, String newVersionId) {
        if (StringUtils.isEmpty(file)) {return;}
        try {
            JSONArray objects = JSONObject.parseArray(file);
            for(int i = 0; i < objects.size(); i++) {
                String filePath = objects.getJSONObject(i).getString("filePath");
                String fileName = objects.getJSONObject(i).getString("fileName");
                if (fileName.length() > 90) {
                    fileName = fileName.substring(fileName.length() - 80, fileName.length() - 1);
                }
                ZsCustomerAttach attach = new ZsCustomerAttach();
                attach.setAttachName(fileName);
                attach.setAttachPath(filePath);
                attach.setAttachType(0);

                String fileType;
                if (fileName.toUpperCase().endsWith("JPG")) {
                    fileType = "0";
                } else if (fileName.toUpperCase().endsWith("PNG")) {
                    fileType = "1";
                } else if (fileName.toUpperCase().endsWith("ZIP")) {
                    fileType = "2";
                } else if (fileName.toUpperCase().endsWith("RAR")) {
                    fileType = "3";
                } else {
                    fileType = "2";
                }
                attach.setFileType(fileType);
                attach.setCreateName("");
                attach.setCreateBy("");
                attach.setCreateDate(LocalDateTime.now());
                attach.setCustomerVersionId(newVersionId);
                attach.setId(getId());
                attachList.add(attach);
            }
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

    }

    private List<ZsCustomerReview> reviewCopy2review(List<ZsCustomerReviewCopy1> reviewCopy1List) {
        List<ZsCustomerReview> list = new LinkedList<>();
        for (ZsCustomerReviewCopy1 reviewCopy : reviewCopy1List) {
            ZsCustomerReview review = new ZsCustomerReview();
            BeanUtils.copyProperties(reviewCopy, review);
            review.setCreateBy("");
            review.setCreateName("");
            list.add(review);
        }
        return list;
    }

    private List<ZsCustomerVersion> versionCopy2version(List<ZsCustomerVersionCopy1> versionCopy1List) {
        List<ZsCustomerVersion> list = new LinkedList<>();
        for (ZsCustomerVersionCopy1 zsCustomerVersionCopy1 : versionCopy1List) {
            ZsCustomerVersion version = new ZsCustomerVersion();
            BeanUtils.copyProperties(zsCustomerVersionCopy1, version);
            version.setName(zsCustomerVersionCopy1.getRealName() == null ? "" : zsCustomerVersionCopy1.getRealName().replaceAll("\\s", ""));
            version.setIdCard(zsCustomerVersionCopy1.getIdcard().replaceAll("\\s", "").toUpperCase());
            version.setMobilePhone(zsCustomerVersionCopy1.getMobile() == null ? null : zsCustomerVersionCopy1.getMobile().replaceAll("\\s", ""));
            version.setCreateBy("");
            version.setCreateName("");
            version.setSystemType(0);
            version.setLegalName(zsCustomerVersionCopy1.getFrName());
            version.setLegalIdCard(zsCustomerVersionCopy1.getFrIdcard());
            version.setLegalMobile(zsCustomerVersionCopy1.getFrMobile());
            version.setVersion(zsCustomerVersionCopy1.getVersion().intValue());
            // 个人大陆
            boolean personAndMainland = version.getCustomerType().equals(1) && version.getCardType().equals(0);
            // 普通企业
            boolean enterpriseAndNomal = version.getCustomerType().equals(0) && version.getOrganType().equals(0);
            if (personAndMainland || enterpriseAndNomal) {
                version.setAuthenticationResult(1);
            } else {
                version.setAuthenticationResult(0);
            }

            list.add(version);
        }
        return list;
    }

    private List<ZsCustomer> customerCopy2customer(List<ZsCustomerCopy1> customerCopy1List) {
        List<ZsCustomer> list = new LinkedList<>();
        for(ZsCustomerCopy1 customerCopy1 : customerCopy1List) {
            ZsCustomer zsCustomer = new ZsCustomer();
            BeanUtils.copyProperties(customerCopy1, zsCustomer);
            zsCustomer.setName(customerCopy1.getRealName() == null ? "" : customerCopy1.getRealName().replaceAll("\\s", ""));
            // zsCustomer.setIdCard(customerCopy1.getIdcard().replaceAll("\\s", "").toUpperCase());
            zsCustomer.setIdCard(customerCopy1.getIdcard());
            zsCustomer.setMobilePhone(customerCopy1.getMobile() == null ? "" : customerCopy1.getMobile().replaceAll("\\s", ""));
            zsCustomer.setHasEqb(0);
            zsCustomer.setRealNameAuth(customerCopy1.getRealNameAuth() <= 1 ? 2 : customerCopy1.getRealNameAuth());
            zsCustomer.setSystemType(0);
            zsCustomer.setUniqueCode(customerCopy1.getUniqueCode() == null ? generateUniqueCode(customerCopy1) : customerCopy1.getUniqueCode());
            zsCustomer.setCreateBy("");
            zsCustomer.setCreateName("");
            zsCustomer.setLegalName(customerCopy1.getFrName());
            zsCustomer.setLegalIdCard(customerCopy1.getFrIdcard());
            zsCustomer.setLegalMobile(customerCopy1.getFrMobile());
            // 个人大陆
            boolean personAndMainland = zsCustomer.getCustomerType().equals(1) && zsCustomer.getCardType().equals(0);
            // 普通企业
            boolean enterpriseAndNomal = zsCustomer.getCustomerType().equals(0) && zsCustomer.getOrganType().equals(0);
            if (personAndMainland || enterpriseAndNomal) {
                zsCustomer.setAuthenticationResult(1);
            } else {
                zsCustomer.setAuthenticationResult(0);
            }
            list.add(zsCustomer);
        }

        return list;
    }

    public String getId() {
        return snowflakeIdWorker.nextId();
    }

    /**
     * 功能描述: 生成唯一编码
     * @param: [zsCustomer]
     * @return: java.lang.String
     * @author: liujin
     * @date: 2020/3/19 14:36
     */
    private String generateUniqueCode(ZsCustomerCopy1 zsCustomer) {
        String code = "ZS";
        code += zsCustomer.getCustomerType().equals(0) ? "P" : "C";
        code += zsCustomer.getCardType().equals(0) ? "L" : "N";
        code += getId();
        //code += System.currentTimeMillis() + String.format("%06d", index);
        return code;
    }
}
